package com.yiyi.credit.manage.abutment.manage.common.interceptor;

import com.yiyi.credit.manage.abutment.client.UserAuthorityManagementClient;
import com.yiyi.credit.manage.abutment.common.bean.Response;
import com.yiyi.credit.manage.abutment.common.enums.ResponseCode;
import com.yiyi.credit.manage.abutment.common.exceptions.ServiceException;
import com.yiyi.credit.manage.abutment.common.utils.TokenUtil;
import org.slf4j.MDC;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

@Configuration
public class CommonInterceptor implements HandlerInterceptor, InitializingBean, ApplicationContextAware {

    private UserAuthorityManagementClient userAuthorityManagementClient = null;

    private ApplicationContext applicationContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if (userAuthorityManagementClient == null) {
            userAuthorityManagementClient = applicationContext.getBean(UserAuthorityManagementClient.class);
        }
        response.setHeader("Access-Control-Allow-Origin", "*");

        MDC.put("rid", UUID.randomUUID().toString().replace("-", "").toLowerCase());

        String path = request.getServletPath();

        if (path.startsWith("/webjars") || path.startsWith("/swagger")
                || path.startsWith("/v2") || path.startsWith("/sub")
                || path.startsWith("/encode") || path.startsWith("/demo")||path.startsWith("/sseSubStation")) {
            return true;
        }

        Cookie tokenCookie = TokenUtil.getCookie(request);

        if (tokenCookie == null) {
            if (path.startsWith("/sseUser/login")) {
                request.setAttribute("sso_login", false);
                return true;
            } else {
                throw new ServiceException(ResponseCode.LOGIN_FIRST);
            }
        }

        String token = tokenCookie.getValue();
        MDC.put("uid", token);
        Response tokenResponse = userAuthorityManagementClient.authToken(token);
        boolean isExist = Objects.equals(tokenResponse.getCode(), "10000");

        if (isExist) {
            request.setAttribute("token", tokenCookie.getValue());
            if (path.startsWith("/sseUser/login")) {
                request.setAttribute("sso_login", true);
            }
            return true;
        }

        if (path.startsWith("/sseUser/login")) {
            request.setAttribute("sso_login", false);
            return true;
        } else {
            tokenCookie.setMaxAge(0);
            response.addCookie(tokenCookie);
            throw new ServiceException(ResponseCode.LOGIN_FIRST);
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e)
            throws Exception {


    }


    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
